<?php
class PaymentConfirmController extends CpController
{
    public $output = array();
    
    public function actionIndex()
    {
        $search = array();
        $search["month"] = isset($_GET["month"]) ? intval($_GET["month"]) : date("m");
        $search["year"] = isset($_GET["year"]) ? intval($_GET["year"]) : date("Y");
        $search["username"] = isset($_GET["username"]) ? Common::cleanQuery($_GET["username"]) : "";
        $search["type"] = isset($_GET["type"]) ? intval($_GET["type"]) : 0;
        
        $currentPage = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
        $currentPage = $currentPage==0 ? 1 : $currentPage;
        $numberRecordPerPage = Yii::app()->params["numberRecordPerPage"];
        
        $paymentConfirm = APaymentConfirm::getPaymentConfirm($search, $currentPage, $numberRecordPerPage);
        $totalPaymentConfirm = APaymentConfirm::getTotalPaymentConfirm($search);
        $numberPage = ceil($totalPaymentConfirm / $numberRecordPerPage);
        
        $this->render(
            "index"
            , array(
                "search"=>$search
                , "paymentConfirm"=>$paymentConfirm                
                , "totalPaymentConfirm"=>$totalPaymentConfirm                
                , "currentPage"=>$currentPage                
                , "numberPage"=>$numberPage
            )
        );   
    }
    
    public function actionDetail()
    {
        $this->layout = false;
        $id = isset($_GET["id"]) ? intval($_GET["id"]): 0;
        
        $paymentConfirm = APaymentConfirm::getPaymentInfo($id);
        
        if(empty($paymentConfirm)){
            throw new CHttpException(404, "Không tìm thấy trang yêu cầu");
        }
        
        $this->render(
            "detail"
            , array(
                "paymentConfirm"=>$paymentConfirm
            )
        );
    }
    
    public function actionExport()
    {
        $this->layout = false;        
        if(isset($_POST["username"])){                    
            
            $search = array();
            $search["username"] = trim(strip_tags($_POST["username"]));
            $search["month"] = intval(trim(strip_tags($_POST["month"])));
            $search["year"] = intval(trim(strip_tags($_POST["year"])));
            $search["type"] = trim(strip_tags($_POST["type"]));
                        
            $currentPage = isset($_GET["currentPage"]) ? intval($_GET["currentPage"]) : 1;
            $currentPage = $currentPage==0 ? 1 : $currentPage;
            $numberRecordPerPage = Yii::app()->params["numberRecordPerPage"];
            
            $paymentConfirm = APaymentConfirm::getPaymentConfirmExport($search);            
                                    
            Yii::import('application.vendors.PHPExcel',true);
            $objPHPExcel = new PHPExcel();            
            $styleArray = array(
                'borders' => array(
                    'allborders' => array(
                        'style' => PHPExcel_Style_Border::BORDER_THIN
                    ),
                ),
            );        
                    
            $objPHPExcel->setActiveSheetIndex(0);        
            $objPHPExcel->getActiveSheet()->setTitle('Xác nhận thanh toán');
            
            /* style mặc định */
            $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);        
            $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);        
            $objPHPExcel->getDefaultStyle()->getAlignment()->setWrapText(true);                            
            
            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
            $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(25);
            $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(35);                    
            $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(50);                    
            
            /* gán dữ liệu */
            $objPHPExcel->getActiveSheet()->mergeCells('A2:G2');        
            $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, 2, 'Xác nhận thanh toán - ' . 'Tháng ' . $search["month"] . " Năm " .  $search["year"]);        
            $objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(14);
            $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(30);
            $objPHPExcel->getActiveSheet()->getStyle('A2:G2')->applyFromArray($styleArray);                        
            $objPHPExcel->getActiveSheet()->getStyle('A2:G2')->getFont()->setBold(true);
            
            $objPHPExcel->getActiveSheet()->setCellValue("A3", 'STT');                    
            $objPHPExcel->getActiveSheet()->setCellValue("B3", 'Tháng');                    
            $objPHPExcel->getActiveSheet()->setCellValue("C3", 'Tài khoản');                    
            $objPHPExcel->getActiveSheet()->setCellValue("D3", 'CMTND');                    
            $objPHPExcel->getActiveSheet()->setCellValue("E3", 'Số tiền');                    
            $objPHPExcel->getActiveSheet()->setCellValue("F3", 'Hình thức nhận tiền');                    
            $objPHPExcel->getActiveSheet()->setCellValue("G3", 'Thông tin người nhận');                    
            
            $objPHPExcel->getActiveSheet()->getStyle('A3:G3')->applyFromArray($styleArray);
            $objPHPExcel->getActiveSheet()->getStyle('A3:G3')->getFont()->setBold(true);
            
            foreach($paymentConfirm as $j=>$row){ 
                
                $i = $j + 4;
                
                $typePayment = "";
                $information = "";
                
                if($row["type"]==1){
                    $typePayment = "Nhận tiền qua tài khoản ATM";
                    $information .= "Tài khoản: " . $row["account_number"] . "\n";
                    $information .= "Chủ tài khoản: " . $row["account_owner"] . "\n";
                    $information .= "Ngân hàng: " . $row["account_bank"] . "\n";
                    $information .= "Chi nhánh: " . $row["account_branch"] . "\n";
                } else if($row["type"]==2){
                    $typePayment = "Nhận tiền qua thẻ cào";
                    $information .= "Số ĐT nhận thẻ: " . $row["mobile_receive"];
                } else if($row["type"]==3){
                    $typePayment = "Nhận tiền qua bưu điện";
                    $information .= "Họ Tên: " . $row["full_name"] . "\n";
                    $information .= "Ngày sinh: " . date("d/m/Y", $row["birthday"]) . "\n";
                    $information .= "Địa chỉ: " . $row["address"] . "\n";
                    $information .= "CMTND: " . $row["identity_number"] . "\n";
                    $information .= "Di động: " . $row["mobile"] . "\n";
                    $information .= "Email: " . $row["email"] . "\n";
                }
                
                $objPHPExcel->getActiveSheet()->getStyle('A' . $i . ':G' . $i)->applyFromArray($styleArray);
                $objPHPExcel->getActiveSheet()->setCellValue("A" . $i, $j+1);
                $objPHPExcel->getActiveSheet()->setCellValue("B" . $i, "Tháng " . $row["month"]);
                $objPHPExcel->getActiveSheet()->setCellValue("C" . $i, $row["username"]);
                
                $objPHPExcel->getActiveSheet()->setCellValueExplicit("D" . $i, $row["identity_number"], PHPExcel_Cell_DataType::TYPE_STRING);
                
                $objPHPExcel->getActiveSheet()->setCellValueExplicit("E" . $i, Common::format_price($row["money"]), PHPExcel_Cell_DataType::TYPE_STRING);
                $objPHPExcel->getActiveSheet()->getStyle('E' . $i)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
                
                $objPHPExcel->getActiveSheet()->setCellValue("F" . $i, $typePayment); 
                $objPHPExcel->getActiveSheet()->setCellValue("G" . $i, $information);
                $objPHPExcel->getActiveSheet()->getStyle('G' . $i)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
                   
                $i++;
            } 
            
            $curr_dir = getcwd();         
            $curr_dir .= "/upload/payment_confirm/" ;            
            $filename = "xac-nhan-thanh-toan-" . date("Y-m-d_H_i_s", time()) . ".xlsx";
            $pathname = $curr_dir . $filename;
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
            $objWriter->save($pathname);
                     
            $link_download = Url::createUrl("paymentConfirm/download", array("p"=>"payment_confirm/", "fn"=>$filename, "fnt"=>$filename));
            $this->output["message"] = $link_download;            
        } else {
            $this->output["status"] = false;            
        }   
        echo json_encode($this->output);                        
    }
    
    public function actionDownload()
    { 
        $this->layout = false;               
        $dir_path = getcwd()."/upload/";                
         
        //lấy tên file cần download từ URL
        $fileNameTrue = isset($_GET['fnt']) ? $_GET['fnt']:'';
        $fileName = isset($_GET['fn']) ? $_GET['fn']:'';
        $filePath = isset($_GET['p']) ? $_GET['p']:'';
        $upload_dir = $dir_path.$filePath;
        
        //thực hiện quá trình kiểm tra
        if (!is_file($upload_dir.$fileName) || !is_readable($upload_dir.$fileName) ) 
        {
            echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
            echo "Tên file không hợp lệ hoặc file ko tồn tại";
            exit(-1);
        }
         
        //mở file để đọc với chế độ nhị phân (binary)
        $fp = fopen($upload_dir.$fileName, "rb");
         
        //gởi header đến cho browser
        header('Content-type: application/octet-stream');
        header('Content-disposition: attachment; filename="'.$fileNameTrue.'"');
        header('Content-length: ' . filesize($upload_dir.$fileName));
         
        //đọc file và trả dữ liệu về cho browser
        fpassthru($fp);
        fclose($fp);
    }
}  
?>
